package network;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.swing.ImageIcon;

import main.Coord;
import main.TDMap;
import towers.Tower;
import towers.TowerTemplate;
import etc.Parser;

public class NetworkClient implements Runnable {

	private BufferedWriter out;
	private BufferedReader in;
	private Socket s;
	private TDMap map;
	private HashMap<String, TowerTemplate> towers;

	public NetworkClient(Socket sock, TDMap map) {
		Set<TowerTemplate> to = Parser.getTowers();
		towers = new HashMap<String, TowerTemplate>();
		for (TowerTemplate t: to) {
			towers.put(t.name, t);
		}
		
		this.map = map;
		try {
			s = sock;
			in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
			out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
		} catch (IOException e) {}
	}

	@Override
	public void run() {
		try {
			while (true) {
				System.out.println("here");
				String str = in.readLine();
				if (str.startsWith("test")) {
					str = str.substring(4);
					str = str.trim();
					print("response: "+str);
				} else if (str.startsWith("tower")) {
					String[] s = str.split(" ");
					String name = s[1].replace("_", " ");
					int x = Integer.parseInt(s[2]);
					int y = Integer.parseInt(s[3]);
					Coord c = new Coord(x, y);
					Tower t = new Tower(towers.get(name));
					t.place(c, map);
					map.addTower(c, t);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
			close();
		}
	}
	
	private void close() {
		try {
			s.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void print(String string) {
		try {
			System.out.println("> "+string);
			out.write(string +"\n");
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
